package com.ruoyi.web.controller.test;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.socket.config.BinanceProxyConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 币安代理配置测试控制器
 */
@RestController
@RequestMapping("/test/binance/proxy")
@Slf4j
public class BinanceProxyTestController {

    @Resource
    private BinanceProxyConfig binanceProxyConfig;

    /**
     * 获取代理配置信息
     */
    @GetMapping("/config")
    public AjaxResult getProxyConfig() {
        try {
            Map<String, Object> config = new HashMap<>();
            config.put("enabled", binanceProxyConfig.isEnabled());
            config.put("host", binanceProxyConfig.getHost());
            config.put("port", binanceProxyConfig.getPort());
            config.put("usernameTemplate", binanceProxyConfig.getUsernameTemplate());
            config.put("currentUsername", binanceProxyConfig.getCurrentUsername());
            config.put("timeout", binanceProxyConfig.getTimeout());
            config.put("currentRandom", binanceProxyConfig.getCurrentRandom());
            config.put("remainingMinutes", binanceProxyConfig.getRemainingMinutes());
            config.put("isValidConfig", binanceProxyConfig.isValidConfig());
            config.put("proxyInfo", binanceProxyConfig.getProxyInfo());
            
            return AjaxResult.success("获取代理配置成功", config);
        } catch (Exception e) {
            log.error("获取代理配置失败", e);
            return AjaxResult.error("获取代理配置失败: " + e.getMessage());
        }
    }

    /**
     * 获取代理状态
     */
    @GetMapping("/status")
    public AjaxResult getProxyStatus() {
        try {
            Map<String, Object> status = new HashMap<>();
            status.put("enabled", binanceProxyConfig.isEnabled());
            status.put("validConfig", binanceProxyConfig.isValidConfig());
            status.put("randomExpired", binanceProxyConfig.isRandomExpired());
            status.put("remainingMinutes", binanceProxyConfig.getRemainingMinutes());
            status.put("currentRandom", binanceProxyConfig.getCurrentRandom());
            status.put("proxyInfo", binanceProxyConfig.getProxyInfo());
            
            return AjaxResult.success("获取代理状态成功", status);
        } catch (Exception e) {
            log.error("获取代理状态失败", e);
            return AjaxResult.error("获取代理状态失败: " + e.getMessage());
        }
    }

    /**
     * 手动刷新随机数
     */
    @PostMapping("/refresh")
    public AjaxResult refreshRandom() {
        try {
            String oldRandom = binanceProxyConfig.getCurrentRandom();
            binanceProxyConfig.refreshRandom();
            String newRandom = binanceProxyConfig.getCurrentRandom();
            
            Map<String, Object> result = new HashMap<>();
            result.put("oldRandom", oldRandom);
            result.put("newRandom", newRandom);
            result.put("newUsername", binanceProxyConfig.getCurrentUsername());
            result.put("remainingMinutes", binanceProxyConfig.getRemainingMinutes());
            
            return AjaxResult.success("刷新随机数成功", result);
        } catch (Exception e) {
            log.error("刷新随机数失败", e);
            return AjaxResult.error("刷新随机数失败: " + e.getMessage());
        }
    }

    /**
     * 测试代理连接
     */
    @PostMapping("/test")
    public AjaxResult testProxyConnection() {
        try {
            if (!binanceProxyConfig.isEnabled()) {
                return AjaxResult.error("代理未启用");
            }
            
            if (!binanceProxyConfig.isValidConfig()) {
                return AjaxResult.error("代理配置无效");
            }
            
            Map<String, Object> testResult = new HashMap<>();
            testResult.put("proxyHost", binanceProxyConfig.getHost());
            testResult.put("proxyPort", binanceProxyConfig.getPort());
            testResult.put("currentUsername", binanceProxyConfig.getCurrentUsername());
            testResult.put("remainingMinutes", binanceProxyConfig.getRemainingMinutes());
            testResult.put("message", "代理配置有效，可以尝试连接");
            
            return AjaxResult.success("代理连接测试完成", testResult);
        } catch (Exception e) {
            log.error("测试代理连接失败", e);
            return AjaxResult.error("测试代理连接失败: " + e.getMessage());
        }
    }

    /**
     * 获取代理统计信息
     */
    @GetMapping("/stats")
    public AjaxResult getProxyStats() {
        try {
            Map<String, Object> stats = new HashMap<>();
            stats.put("enabled", binanceProxyConfig.isEnabled());
            stats.put("configValid", binanceProxyConfig.isValidConfig());
            stats.put("currentRandom", binanceProxyConfig.getCurrentRandom());
            stats.put("timeoutMinutes", binanceProxyConfig.getTimeout());
            stats.put("remainingMinutes", binanceProxyConfig.getRemainingMinutes());
            stats.put("randomExpired", binanceProxyConfig.isRandomExpired());
            stats.put("proxyInfo", binanceProxyConfig.getProxyInfo());
            
            // 计算使用率
            long remainingMinutes = binanceProxyConfig.getRemainingMinutes();
            int timeoutMinutes = binanceProxyConfig.getTimeout();
            double usageRate = timeoutMinutes > 0 ? 
                (double)(timeoutMinutes - remainingMinutes) / timeoutMinutes * 100 : 0;
            stats.put("usageRate", Math.round(usageRate * 100.0) / 100.0);
            
            return AjaxResult.success("获取代理统计信息成功", stats);
        } catch (Exception e) {
            log.error("获取代理统计信息失败", e);
            return AjaxResult.error("获取代理统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 获取代理配置验证信息
     */
    @GetMapping("/validate")
    public AjaxResult validateProxyConfig() {
        try {
            Map<String, Object> validation = new HashMap<>();
            validation.put("enabled", binanceProxyConfig.isEnabled());
            validation.put("validConfig", binanceProxyConfig.isValidConfig());
            
            // 详细验证信息
            Map<String, Boolean> details = new HashMap<>();
            details.put("hostValid", binanceProxyConfig.getHost() != null && !binanceProxyConfig.getHost().trim().isEmpty());
            details.put("portValid", binanceProxyConfig.getPort() > 0 && binanceProxyConfig.getPort() <= 65535);
            details.put("usernameTemplateValid", binanceProxyConfig.getUsernameTemplate() != null && !binanceProxyConfig.getUsernameTemplate().trim().isEmpty());
            details.put("passwordValid", binanceProxyConfig.getPassword() != null && !binanceProxyConfig.getPassword().trim().isEmpty());
            details.put("timeoutValid", binanceProxyConfig.getTimeout() > 0);
            details.put("randomGenerated", binanceProxyConfig.getCurrentRandom() != null);
            
            validation.put("details", details);
            validation.put("proxyInfo", binanceProxyConfig.getProxyInfo());
            
            return AjaxResult.success("代理配置验证完成", validation);
        } catch (Exception e) {
            log.error("验证代理配置失败", e);
            return AjaxResult.error("验证代理配置失败: " + e.getMessage());
        }
    }
} 